package org.apimgr.interceptor;


import org.apimgr.annotation.AuthReq;
import org.apimgr.constants.StringConstants;
import org.apimgr.entity.ApiUser;
import org.apimgr.enums.PTExceptionCode;
import org.apimgr.exception.PTUnCheckedException;
import org.apimgr.service.LoginService;
import org.apimgr.util.RespJson;
import org.apimgr.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * Created by yangjie on 2017/8/2.
 */
@Aspect
@Component
public class AuthInterceptor {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Resource
    private LoginService loginService;


    /**
     *
     * @param joinPoint  拦截点
     * @param requestMapping  请求
     * @param authReq  标识为需要鉴权的请求
     * @return
     * @throws Throwable  Throwable 异常
     */
    @Around("within(org.apimgr..*) && @annotation(requestMapping) && @annotation(authReq)")
    public Object aroundController(ProceedingJoinPoint joinPoint, RequestMapping requestMapping, AuthReq authReq) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //获取前台传参：token
        String token = "";
        for(int i=0;i<signature.getParameterNames().length;i++){
            if(StringConstants.TOKEN.equals(signature.getParameterNames()[i])){
                token = (String) joinPoint.getArgs()[i];
                break;
            }
        }


        if(StringUtils.isEmpty(token)){
            logger.error(PTExceptionCode.SYS_AUTH_TOKEN_ERROR.getDesout());
            return RespJson.buildFailureResponse(PTExceptionCode.SYS_AUTH_TOKEN_ERROR.getDesout());
        }

        //获取当前登录用户对象
        ApiUser apiUser = null;

        try {
            apiUser = loginService.getLoginUser(token);
        } catch (PTUnCheckedException e) {
            return RespJson.buildFailureResponse( e.getOutMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return RespJson.buildFailureResponse(StringConstants.SYSTEM_ERROR);
        }

        logger.info("操作鉴权成功:"+apiUser.getUsername());
        logger.info("控制器: " + method.getDeclaringClass().getName().substring(22));
        logger.info("函数名: " + method.getName());
        logger.info("请求路径: " + requestMapping.value()[0]);

        return joinPoint.proceed(); // 返回调用方法的结果
    }
}
